<template>
    <!-- 组装拆卸页面 -->
    <div class="app-container transfer-page">
        <el-form ref="form" :model="form" label-width="80px">
            <el-row :gutter="10" class="sumbit-btn-group mb8">
                <el-col class="flex-center" :span="1.5">
                    <el-form-item label="单据日期">
                        <el-date-picker
                            v-model="form.receiptsTime"
                            type="date"
                            placeholder="选择日期"
                        />
                    </el-form-item>
                </el-col>
                <el-col class="flex-center" :span="1.5">
                    <span class="sub-text"
                        >单据编号: {{ form.assembleId }}</span
                    >
                </el-col>
                <el-col class="flex-center" :span="3">
                    <JustTimeInventory @selectItemsClick="selectItemsClick" :single="true" />
                </el-col>

                <div class="empty"></div>
                <el-col :span="1.5">
                    <el-button
                        type="primary"
                        plain
                        size="mini"
                        @click="saveAssembly(1)"
                        v-hasPermi="['storage:woodAssemble:add']"
                        >{{id ? '新增':'保存并新增'}}</el-button
                    >
                </el-col>
                <el-col :span="1.5">
                    <el-button
                        type="success"
                        plain
                        size="mini"
                        @click="saveAssembly(0)"
                        v-hasPermi="['storage:woodAssemble:add']"
                        >保存</el-button
                    >
                </el-col>

                <el-col :span="1.5" v-if="id">
                    <el-button
                        type="success"
                        plain
                        size="mini"
                        @click="handleAudit()"
                        v-hasPermi="['storage:woodAssemble:editAssembleAuditState']"
                        >{{
                            form.auditStatus == 1 ? "反审核" : "审核"
                        }}</el-button
                    >
                </el-col>

                <el-col :span="1.5">
                    <el-button
                        plain
                        size="mini"
                        @click="
                            $router.push({
                                path: '/depot/receipt/assembly/list',
                            })
                        "
                         v-hasPermi="['storage:woodAssemble:list']"
                        >历史单据</el-button
                    >
                </el-col>
            </el-row>

            <div class="table-area">
                <div class="table-title">待出库</div>
                <TableForm
                    :loading="loading"
                    :column="depot.outColnm"
                    :list="depot.outData"
                    :hideAdd="true"
                    :beforeDel="depotOutDelCheck"
                    height="30vh"
                />

                <div class="table-title">待入库</div>
                <TableForm
                    :loading="loading"
                    :column="depot.inColnm"
                    :list="depot.inData"
                    :beforeAdd="depotInAddCheck"
                    :beforeDel="depotInDelCheck"
                    height="30vh"
                    ref="TableForm"
                />

                <el-form-item class="form-remark" prop="remark">
                    <el-input
                        v-model="form.remark"
                        type="textarea"
                        placeholder="请输入备注信息"
                        clearable
                        size="small"
                        rows="2"
                        :disabled="disabled"
                    />
                </el-form-item>
            </div>
        </el-form>
    </div>
</template>

<script>
import TableForm from "@/components/TableForm/preset";
import JustTimeInventory from "@/components/JustTimeInventory";
export default {
    components: {
        TableForm,
        JustTimeInventory,
    },
    data: () => {
        return {
            id: "",
            disabled: false,
            form: {
                assembleId: "",
                receiptsTime: Date.now(),
                auditStatus: 0,
                woodAssembleGoodsList: [],
                remark: "",
            },
            depot: {
                inData: [],
                inColnm: [],
                outData: [],
                outColnm: [],
            },
            loading: false,
        };
    },
    created() {
        let { id } = this.$route.params;

        this.setTableCoulnm("in");
        this.setTableCoulnm("out");

        id ? this.getAssemblyDetail(id) : this.resetData();
    },
    methods: {
        handleAudit() {
            let { id, loading } = this;

            if (loading) return;
            this.loading = true;

            let { auditStatus } = this.form;
            let _auditStatus = auditStatus ? 0 : 1;
            this.$Api.storage.assemble
                .audit({
                    assembleIdArray: [id],
                    auditStatus: _auditStatus,
                })
                .then((res) => {
                    this.form.auditStatus = _auditStatus;
                    this.$message.success("操作成功");
                    this.loading = false;
                })
                .catch(() => {
                    this.loading = false;
                });
        },
        // 获取详情
        getAssemblyDetail(id) {
            this.id = id;
            //  let { inData, outData } = this.depot;

            this.$Api.storage.assemble.detail(id).then((res) => {
                let inData = [];
                let outData = [];

                let d = res.data;
                d.woodAssembleGoodsList.forEach((v) => {
                    // v.inCount = v.allotInCount;
                    v.type == 2 ? inData.push(v) : outData.push(v);
                });
                this.form = d;
                this.depot.inData =  inData;
                this.depot.outData =  outData;
            });
        },
        //    初始化列表
        setTableCoulnm(k) {
            let arr = [
                { label: "包号", inputType: "none" },
                { label: "品名", inputType: "none" },
                { label: "品牌", inputType: "none" },
                { label: "等级", inputType: "none" },
                { label: "仓库", inputType: "none" },
                { label: "厚度", inputType: "none" },
                { label: "宽度", inputType: "none" },
                { label: "长度", inputType: "none" },
                { label: "片数", inputType: "none" },
                { label: "件数", inputType: "none" },
                { label: "单包方数", checkSame: false, inputType: "none" },
                { label: "方数", checkSame: false, inputType: "none" },
                { label: "成本单价", inputType: "none" },
                { label: "货物状态", inputType: "none" },
                { label: "产地", inputType: "none" },
                { label: "提单号", inputType: "none" },
                { label: "合同号", inputType: "none" },
                { label: "开证公司", inputType: "none" },
                { label: "备注", inputType: "none" },
            ];

            k === "in" &&
                arr.forEach((v) => {
                    if (["包号", "件数"].includes(v.label)) {
                        delete v.inputType;
                    }
                });

            this.depot[`${k}Colnm`] = arr;
        },
        resetData() {
            this.getId();
            this.setData("in");
            this.setData("out");
        },
        // 重置列表数据
        setData(k) {
            let obj = {
                assembleId: "",
                baleNum: "",
                brandName: "",
                createBy: "",
                createTime: "",
                delFlag: "",
                gcountId: "",
                goodsName: "",
                goodsState: "",
                inCount: 0,
                itemId: "",
                ladingNum: "",
                length: 0,
                level: "",
                oneCount: 0,
                originPlace: "",
                pactName: "",
                pactNum: "",
                params: {},
                pieceCount: 0,
                ply: 0,
                remark: "",
                searchValue: "",
                sliceCount: 0,
                storageLocation: "",
                unitCost: 0,
                updateBy: "",
                updateTime: "",
                warehouse: "",
                width: 0,
            };
            this.depot[`${k}Data`] = [obj];
        },
        selectItemsClick(data) {
            
            let outData = JSON.parse(JSON.stringify(data));
            let inData = JSON.parse(JSON.stringify(data));

            outData.forEach((v,i) => {
                v.type = 1;
            });

            inData.forEach((v,i) => {
                v.type = 2;
            });

            this.depot = {
                inData,
                outData,
            };
        },
        depotInAddCheck(d, form, i) {
            let { split } = this;
            let { pieceCount, gcountId } = d;
            if (pieceCount <= 1) {
                this.$message.error("商品必须大于一件才可以拆分不可拆分");
            } else {
                let p = Number((pieceCount * 0.5).toFixed(0));
                let d1 = JSON.parse(JSON.stringify(d));
                let d2 = JSON.parse(JSON.stringify(d));

                // 均分
                d1.pieceCount = p;
                d2.pieceCount = p;
                pieceCount % 2 && d2.pieceCount--;
                form.data.splice(i, 1, d1, d2);
            }

            return false;
        },
        depotInDelCheck(d, form, i) {
            let { pieceCount, gcountId } = d;
        },
        depotOutDelCheck(d, form, i) {
            let { inData } = this.depot;
            let newInData = [];
            let { gcountId } = d;
            inData.forEach((v) => {
                v.gcountId != gcountId && newInData.push(v);
            });
            this.depot.inData = newInData;
        },
        saveAssembly(clear) {
            let { form, loading, id } = this;
            let { inData, outData } = this.depot;
            let { TableForm } = this.$refs;
            let check = true;

            if (loading) return false;

            // outData.forEach((outItem) => {
            for (let i = 0; i < outData.length; i++) {
                let count = 0;
                let outItem = outData[i];
                let { gcountId, pieceCount, baleNum } = outItem;
                inData.forEach((inItem) => {
                    let _gcountId = inItem.gcountId;
                    let _pieceCount = inItem.pieceCount;
                    _gcountId === gcountId && (count += Number(_pieceCount));
                });

                console.log(count, pieceCount);
                if (count != pieceCount) {
                    this.$message.error(
                        `包号：[${baleNum}] 的拆卸件数与原件数不一致`
                    );
                    check = false;
                    break;
                }
            }

            if (!check) return false;
            form.woodAssembleGoodsList = [...inData, ...outData];

            TableForm.checkForm((pass) => {
                if (pass) {
                    this.loading = true;
                    let { add, update } = this.$Api.storage.assemble;
                    let api = id ? update : add;
                    api(form)
                        .then((res) => {
                            let { msg, code } = res;
                            this.id = form.assembleId;
                            this.loading = false;
                            this.$message.success(msg);
                            code == 200 && clear && this.resetData();
                        })
                        .catch(() => {
                            this.loading = false;
                        });
                }
            });
        },
        getId() {
            this.$Api.onlyId.getId().then((res) => {
                this.form.assembleId = res.data || "";
            });
        },
    },
};
</script>

<style lang="scss" scoped>
::v-deep.transfer-page {
    .sumbit-btn-group {
        position: relative;
        z-index: 100;
        margin: 10px 0 20px 0;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .empty {
            width: 100%;
            flex: 1;
        }
        .sub-text {
            margin-left: 20px;
            font-size: 12px;
            color: #262626;
            user-select: none;
        }

        .supplier-select {
            .add-wood-just-time {
                margin: 0;
            }
        }
    }

    .el-form-item {
        margin: 0;
    }
    .form-remark {
        display: block;
        display: block;
        margin: 20px 15px 15px;
        .el-form-item__content {
            margin: 0 !important;
            width: 100%;
        }
    }

    // .table-form-com {
    //     & + .table-form-com {
    //         margin-top: 20px;
    //     }
    // }

    .table-area {
        padding-top: 0;
        .table-title {
            padding: 20px 0 10px 20px;
            font-size: 14px;
            color: #262626;
        }
    }
}
</style>

